/*
#####################################################################
####################	   T R I B U I T 		#####################
#####################################################################

Copyright (C) 2010  Christoph Schnack, Berlin (Germany)

This file is part of Tribuit.

    Tribuit is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Tribuit is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tribuit.  If not, see <http://www.gnu.org/licenses/>.


########################################################################
*/
package PictureDescription;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.HashMap;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import GuiTools.*;
import Mainframe.*;
import PictureDescription.Lesson;
import Settings.*;

/**
 * Dialog for creating and editing lessons with pictures from all collections.
 * 
 * @author Christoph Schnack
 *
 */
public class PictureLessonsDialog {
	MDTribuitFrame pedFrame;
	Mainframe MAINFRAME;
	Settings SET;
	Language LANG;
	MDManager PMDM;
	PictureStorage PICSTO;
	MDTribuitFrame pldFrame;
	HashMap<String,Lesson> lessons;
	JList destList,sourceList;
	JComboBox lessonsCB,collCB,sectionCB;
	TribuitTextField newLessonNameTF;
	PreviewPanel destPreviewPanel,sourcePreviewPanel;
	JRadioButton allRB,sectionRB;
	PUListModel destListModel, sourceListModel;
	JButton deleteLessonBtn,editLessonNameBtn;
	
	public PictureLessonsDialog(PictureStorage picsto,Settings set,Mainframe mf,MDManager pmdm){
		SET=set;
		LANG=SET.getLanguage();
		PICSTO=picsto;
		MAINFRAME=mf;
		PMDM=pmdm;
		//copy PictureStorage's data
		lessons = new HashMap<String,Lesson>();
		Lesson lesson, oldLesson;
		for(String key : PICSTO.getLessons().keySet().toArray(new String[]{})){
			lesson = new Lesson(PICSTO);
			oldLesson = PICSTO.getLesson(key);
			for(String coll : oldLesson.getCollectionNames()){
				if(oldLesson.getUnitNames(coll)!=null){
					for(String name : oldLesson.getUnitNames(coll)){
						lesson.addUnit(coll, name);
					}
				}
			}
			lessons.put(key, lesson);
		}
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				buildGUI();
			}
		});
	}
	
	public void buildGUI(){
		pldFrame = new MDTribuitFrame(LANG.getEditLessons(),PMDM);
		
		sourcePreviewPanel = new PreviewPanel(LANG.getPreview());
		destPreviewPanel = new PreviewPanel(LANG.getPreview());
		sourceListModel = new PUListModel();
		sourceList = new JList(sourceListModel);
		sourceList.addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent arg0) {
				if(!sourceList.isSelectionEmpty() && sourceList.getSelectedValue()!=null)sourcePreviewPanel.setImage((String)collCB.getSelectedItem(),(String)sourceList.getSelectedValue());
			}
		});
		sourceList.addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent e) {
				if(!sourceList.isSelectionEmpty() && sourceList.getSelectedValue()!=null){
					if(e.getClickCount()>=2){
						if(lessonsCB.getItemCount()>0){
							lessons.get((String)lessonsCB.getSelectedItem()).addUnit((String)collCB.getSelectedItem(), (String)sourceListModel.elementAt(sourceList.getSelectedIndex()));
							updateDestListModel();
						}
						else{
							JOptionPane.showMessageDialog(pldFrame, LANG.getPleaseCreateLessonFirst(), LANG.getAttention(), JOptionPane.WARNING_MESSAGE);
						}
					}
				}
			}
		});
		JScrollPane sourceListSP = new JScrollPane(sourceList);
		sourceListSP.setPreferredSize(new Dimension(150,200));
		allRB = new JRadioButton(LANG.getAll(),true);
		allRB.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				sectionCB.setEnabled(false);
				sourceListModel.removeAllElements();
				String coll = (String)collCB.getSelectedItem();
				Vector<PictureUnit> units = PICSTO.getCollection(coll).getPictureUnits();
				for(int i=0;i<units.size();i++){
					sourceListModel.addElement(units.elementAt(i).getName());
				}
			}
		});
		sectionRB = new JRadioButton(LANG.getSection());
		sectionRB.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				sectionCB.setEnabled(true);
				sourceListModel.removeAllElements();
				for(PictureUnit pu : PICSTO.getCollection((String)collCB.getSelectedItem()).getPictureUnitsOfSection((String)sectionCB.getSelectedItem())){
					sourceListModel.addElement(pu.getName());
				}
			}
		});
		ButtonGroup sBg = new ButtonGroup();
		sBg.add(allRB);
		sBg.add(sectionRB);
		sectionCB = new JComboBox();
		sectionCB.setPreferredSize(new Dimension(150,sectionCB.getPreferredSize().height));
		sectionCB.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				sourceListModel.removeAllElements();
				for(PictureUnit pu : PICSTO.getCollection((String)collCB.getSelectedItem()).getPictureUnitsOfSection((String)sectionCB.getSelectedItem())){
					sourceListModel.addElement(pu.getName());
				}
			}
		});
		collCB = new JComboBox(PICSTO.getCollectionNames());
		collCB.setPreferredSize(new Dimension(150,collCB.getPreferredSize().height));
		collCB.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String coll = (String)collCB.getSelectedItem();
				sectionCB.removeAllItems();
				Vector<String> chapter = PICSTO.getCollection(coll).getSections();
				for(String chap : chapter){
					sectionCB.addItem(chap);
				}
				SwingUtilities.invokeLater(new Runnable(){
					public void run(){
						if(allRB.isSelected()) allRB.doClick();
						else sectionRB.doClick();
					}
				});
			}
		});
		JPanel sectionPanel = new JPanel();
		sectionPanel.add(sectionRB);
		sectionPanel.add(allRB);
		allRB.doClick();
		
		JPanel sourcePanel = new JPanel(new GridBagLayout());
		sourcePanel.setBorder(BorderFactory.createTitledBorder(LANG.getCollections()));
		GridBagConstraints sGbc = new GridBagConstraints();
		sGbc.anchor = GridBagConstraints.NORTHWEST;
		sGbc.fill = GridBagConstraints.BOTH;
		sGbc.gridy = 1;
		sGbc.gridx = 1;
		sourcePanel.add(collCB,sGbc);
		sGbc.gridy = 2;
		sourcePanel.add(sectionPanel,sGbc);
		sGbc.gridy = 3;
		sGbc.fill = GridBagConstraints.NONE;
		sourcePanel.add(sectionCB,sGbc);
		sGbc.gridy = 4;
		sourcePanel.add(sourceListSP,sGbc);
		sGbc.fill = GridBagConstraints.NONE;
		sGbc.gridy = 1;
		sGbc.gridx = 2;
		sGbc.gridheight = 4;
		sGbc.anchor = GridBagConstraints.SOUTH;
		sourcePanel.add(sourcePreviewPanel,sGbc);
		
		
		destListModel = new PUListModel();
		destList = new JList(destListModel);
		destList.addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent arg0) {
				if(!destList.isSelectionEmpty() && destList.getSelectedValue()!=null){
					String selection = (String)destList.getSelectedValue();
					String[] split = selection.split(":");
					destPreviewPanel.setImage(split[0],split[1].trim());
				}
			}
			
		});
		destList.addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent e) {
				if(!destList.isSelectionEmpty() && destList.getSelectedValue()!=null){
					if(e.getClickCount()>=2){
						String[] split = ((String)destList.getSelectedValue()).split(":");
						lessons.get((String)lessonsCB.getSelectedItem()).deleteUnitFromCollection(split[0],split[1].trim(),false);
						//destListModel.remove(destList.getSelectedIndex());
						updateDestListModel();
						destPreviewPanel.setNoImage();
					}
				}
			}
		});
		JScrollPane destListSP = new JScrollPane(destList);
		destListSP.setPreferredSize(new Dimension(150,200));
		collCB.setSelectedIndex(0);
		
		
		newLessonNameTF = new TribuitTextField(SET,5);
		JButton newLessonBtn = new JButton(LANG.getNew());
		newLessonBtn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String newName = JOptionPane.showInputDialog(pldFrame, LANG.getNewLessonName()+":");
				if(newName == null) return;
				if(newName.equals("")){
					GuiTools.showEmptyOrInvalidInputWarning(LANG, pldFrame, LANG.getNewLessonName());
					return;
				}
				if(lessons.containsKey(newName)){
					JOptionPane.showMessageDialog(pldFrame, LANG.getLessonNameAlreadyExists(), LANG.getAttention(), JOptionPane.WARNING_MESSAGE);
					return;
				}
				lessons.put(newName, new Lesson(PICSTO));
				lessonsCB.addItem(newName);
				updateDestListModel();
				pldFrame.pack();
			}
		});
		deleteLessonBtn = new JButton(LANG.getDelete());
		deleteLessonBtn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				int choice = JOptionPane.showOptionDialog(pldFrame, LANG.getReallyDeleteLesson(), LANG.getQuestion(),  JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, new String[]{LANG.getYes(),LANG.getNo()}, LANG.getNo());
				if(choice == JOptionPane.YES_OPTION){
					lessons.remove((String)lessonsCB.getSelectedItem());
					lessonsCB.removeItem((String)lessonsCB.getSelectedItem());
					if(lessonsCB.getItemCount()==0) setEditButtonsEnabled(false);
					pldFrame.pack();
				}
			}
		});
		editLessonNameBtn = new JButton(LANG.getEdit());
		editLessonNameBtn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String oldName = (String)lessonsCB.getSelectedItem();
				String newName = JOptionPane.showInputDialog(pldFrame, LANG.getEditName()+" ("+oldName+") :");
				if(newName==null) return;
				if(newName.equals("")){
					GuiTools.showEmptyOrInvalidInputWarning(LANG, pldFrame, LANG.getEditName());
					return;
				}
				if(lessons.containsKey(newName)){
					JOptionPane.showMessageDialog(pldFrame, LANG.getLessonNameAlreadyExists(), LANG.getAttention(), JOptionPane.WARNING_MESSAGE);
					return;
				}
				Lesson l = lessons.get(oldName);
				lessons.put(newName, l);
				lessons.remove(oldName);
				lessonsCB.addItem(newName);
				lessonsCB.removeItem(oldName);
				updateDestListModel();
				pldFrame.pack();
			}
		});
		
		lessonsCB = (lessons.isEmpty())?new JComboBox():new JComboBox(lessons.keySet().toArray(new String[]{}));
		lessonsCB.setPreferredSize(new Dimension(150,lessonsCB.getPreferredSize().height));
		lessonsCB.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				updateDestListModel();
			}
		});
		if(!lessons.isEmpty())lessonsCB.setSelectedIndex(0);

		JPanel editButtonsPanel = new JPanel();
		editButtonsPanel.add(newLessonBtn);
		editButtonsPanel.add(editLessonNameBtn);
		editButtonsPanel.add(deleteLessonBtn);
		JPanel editPanel = new JPanel();
		editPanel.setBorder(BorderFactory.createTitledBorder(LANG.getEditLessons()));
		editPanel.setLayout(new GridBagLayout());
		GridBagConstraints eGbc = new GridBagConstraints();
		eGbc.anchor = GridBagConstraints.WEST;
		eGbc.fill = GridBagConstraints.NONE;
		eGbc.gridwidth = 2;
		eGbc.gridx = 1;
		editPanel.add(new JLabel(LANG.getLesson()),eGbc);
		eGbc.gridy=1;
		editPanel.add(lessonsCB,eGbc);
		eGbc.gridy = 2;
		editPanel.add(editButtonsPanel,eGbc);
		eGbc.gridy = 3;
		eGbc.gridwidth = 1;
		editPanel.add(destListSP,eGbc);
		eGbc.gridx = 2;
		eGbc.fill = GridBagConstraints.NONE;
		editPanel.add(destPreviewPanel,eGbc);
		
		JPanel centerPanel = new JPanel();
		centerPanel.add(editPanel);
		centerPanel.add(sourcePanel);
		centerPanel.setBackground(Color.gray);
		//ButtonPanel
		JButton okBtn = new JButton(LANG.getAccept()), cancelBtn = new JButton(LANG.getCancel());
		okBtn.addActionListener(new OkBtnListener());
		cancelBtn.addActionListener(new CancelBtnListener());
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBackground(GuiTools.BGCOLOR);
		buttonPanel.add(okBtn);
		buttonPanel.add(cancelBtn);
		pldFrame.getContentPane().add(BorderLayout.NORTH,new Header(LANG.getLessons()));
		pldFrame.getContentPane().add(BorderLayout.CENTER, centerPanel);
		pldFrame.getContentPane().add(BorderLayout.SOUTH,buttonPanel);
		pldFrame.showUp(200,200);
		updateDestListModel();
	}
	
	public void updateDestListModel(){
		if(lessonsCB.getItemCount()>0){
			lessonsCB.setEnabled(true);
			setEditButtonsEnabled(true);
			Lesson less = lessons.get((String)lessonsCB.getSelectedItem());
			destListModel.removeAllElements();
			if(less!=null){
				for(String s : less.getCollectionNames()){
					for(String t : less.getUnitNames(s)){
						destListModel.addElement(s+": "+t);
					}
				}
			}
		}
		else{
			lessonsCB.setEnabled(false);
			setEditButtonsEnabled(false);
		}
	}
	
	public void setEditButtonsEnabled(boolean enabled){
		editLessonNameBtn.setEnabled(enabled);
		deleteLessonBtn.setEnabled(enabled);
		
	}
	
	class OkBtnListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			PICSTO.setLessons(lessons);
			PICSTO.saveLessons();
			pldFrame.dispose();
			new PictureManageDialog(PICSTO, SET, MAINFRAME, PMDM);
		}
	}
	
	class CancelBtnListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			pldFrame.dispose();
			new PictureManageDialog(PICSTO, SET, MAINFRAME, PMDM);
		}
	}
	
	class PUListModel extends DefaultListModel{
		public PUListModel(){
			super();
		}
		
		public String[] getAllElements(){
			String[] result = new String[getSize()];
			for(int i=0;i<getSize();i++){
				result[i] = (String)get(i);
			}
			return result;
		}
	}
}
